<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\FlyCart;
use App\Model\Product;
use App\Model\ProductSpecKey;
use App\Model\ProductSpecValue;
use App\Model\Sku;
use App\Model\SkuPrice;
use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Annotation\Inject;
use function Symfony\Component\Translation\t;

class SkuService extends BaseService
{

    /**
     * //    sku信息
     * @param int $sku_id
     * @return object
     */
    public function info(int $sku_id)
    {
       return Sku::query()
            ->where('sku_id',$sku_id)
            ->with(['step_price', 'with_product', 'file_info', 'industry_info'])
            ->first();
    }

    /**
     * //    发布
     * @param array $skuData
     * @param int $product_id
     * @param int $type 1是增量发布  2全新发布，删除旧数据
     * @return array
     */
    public function sku_insert(array $skuData, int $product_id, int $type = 1)
    {
//        回退的部分要删除。
        if ($type == 2) {
            $res1 = Sku::query()->where('product_id', $product_id)->delete();
            $res2 = ProductSpecValue::query()->where('product_id', $product_id)->delete();
            $res3 = FlyCart::query()->where('product_id', $product_id)->delete();
        }
        $arr = [];
//        $spec_key = ProductSpecKey::query()->where('product_id', $product_id)->orderBy('id','DESC')->pluck('id');
//        if ($spec_key) {
//            $spec_key = $spec_key->toArray();
//        }
        $lows = [];
        $shop_info =  CurrentShopData::getData();
        foreach ($skuData as $key => $value) {
            $step_price = $spec_value = [];
            if (isset($value['step_price'])) {
                $step_price = $value['step_price'];
                unset($value['step_price']);
            }
            if (isset($value['spec_value'])) {
                $spec_value = $value['spec_value'];
                unset($value['spec_value']);
            }
            $value['product_id'] = $product_id;
            $value['shop_id'] = $shop_info->id;
            if( isset($value['inventory'])&&$value['inventory']!=''){
                $value['inventory'] = $value['inventory'];
            }else{
                $value['inventory'] = -1;
            }

            if($step_price){
                $lows[] = $value['sku_min_price'] = $this->get_low_price($step_price);
            }

            if(count($step_price)>1){
                $value['is_step_price'] = 1;
            }else{
                $value['is_step_price'] = 0;
            }
            $sku_id = '';
            $arr[] = $sku_id = $this->insertAndGetId(Common::filter_null($value));


//            插入参数 key value
            $this->spec_value_insert($spec_value, $product_id, $sku_id, 1);

            //            判断阶梯价是否合理
            if (Common::check_step_price($step_price)) {
                //插入阶梯价
                $this->step_price_insert($step_price, $sku_id,$product_id);
            } else {
                throw new \RuntimeException("阶梯价不合理在第：" . ($key + 1) . '个规格', ErrorCode::SYSTEM_INVALID);
            }
        }
        if ($lows) {
            ksort($lows, 1);
            Product::query()->where('id', $product_id)->update(['min_single_price' => $lows['0']]);
        }
        return $arr;
    }


//    获取最低价
    public function get_low_price(array $step_price)
    {
        $price = array_column($step_price, 'price');
        sort($price, 1);
        return $price['0'];
    }

    /**
     * @param array $skuData
     * @param int $product_id
     * @param array $spec_key
     * @param int $type 1基本修改默认  2全新膝盖，删除旧数据
     * @return bool
     */
    //    全新修改
    public function sku_update(array $skuData, int $product_id, $type = 1)
    {
//        原先的部分要删除。
        if ($type == 2) {
            $res1 = Sku::query()->where('product_id', $product_id)->delete();
            $res3 = FlyCart::query()->where('product_id', $product_id)->delete();
        }
//        $spec_key = ProductSpecKey::query()->where('product_id', $product_id)->pluck('id');
//        if ($spec_key) {
//            $spec_key = $spec_key->toArray();
//        }
        $lows = [];
        $shop_info =  CurrentShopData::getData();
        foreach ($skuData as $key => $value) {
            $step_price = $spec_value = [];
            if (isset($value['step_price'])) {
                $step_price = $value['step_price'];
                unset($value['step_price']);
            }
            if (isset($value['spec_value'])) {
                $spec_value = $value['spec_value'];
                unset($value['spec_value']);
            }
            $value['product_id'] = $product_id;
            $value['inventory'] = $value['inventory'] === '' ? -1 : $value['inventory'];

            $value['shop_id'] = $shop_info->id;
            $lows[] = $value['sku_min_price'] = $this->get_low_price($step_price);

            if(count($step_price)>1){
                $value['is_step_price'] = 1;
            }else{
                $value['is_step_price'] = 0;
            }
            if(isset($value['sku_id'])&&$value['sku_id']!=0){
                $sku_id = $value['sku_id'];
                $this->update_insert([
                    'sku_id' => $sku_id,
                    'shop_id' => $value['shop_id'],
                ], Common::filter_null($value));
            }else{
                $sku_id = $this->insertAndGetId(Common::filter_null($value));
            }
//            插入参数 key value
            $this->spec_value_insert($spec_value, $product_id, $sku_id, 2);
            //            判断阶梯价是否合理
            if (Common::check_step_price($step_price)) {
                //插入阶梯价
                $this->step_price_insert($step_price, $sku_id, $product_id,2);
            } else {
                throw new \RuntimeException("阶梯价不合理在第：" . ($key + 1) . '个规格', ErrorCode::SYSTEM_INVALID);
            }
        }
        if ($lows) {
            ksort($lows, 1);
            Product::query()->where('id', $product_id)->update(['min_single_price' => $lows['0']]);
        }
        return true;
    }


    //    阶梯价插入
    public function step_price_insert(array $step_price, $sku_id, $product_id,$type = 1)
    {
        //            插入参数 key value
        if ($type == 2) {
            SkuPrice::query()->where('sku_id', $sku_id)->delete();
        }
        //            插入参数 key value
        if (count($step_price) > 0) {
            $value_arr = [];
            foreach ($step_price as $k => $v) {
                if ($step_price[$k]) {
                    $value_arr[] = [
                        'num' => $v['num'],
                        'single_price' => $v['price'],
                        'sku_id' => $sku_id,
                        'product_id' => $product_id,
                    ];
                }
                $min_price = $v['price'];
            }
            if (count($value_arr) > 0) {
                SkuPrice::query()->insert($value_arr);
            }
        }
        return true;
    }

    //    sku_value插入
    public function spec_value_insert(array $spec_value, $product_id, $sku_id, $type = 1)
    {
        //            插入参数 key value
        if ($type == 2) {
            ProductSpecValue::query()->where('sku_id', $sku_id)->delete();
        }
        if (count($spec_value) > 0 && count($spec_value) > 0) {
            $value_arr = [];
            foreach ($spec_value as $k => $v) {
                if ($v['key_id']&&$v['value']) {
                    $value_arr[] = [
                        'spec_key' => $v['key_id'],
                        'spec_value' => $v['value'],
                        'product_id' => $product_id,
                        'sku_id' => $sku_id,
                    ];
                }
            }
            if (count($value_arr) > 0) {
                ProductSpecValue::query()->insert($value_arr);
            }
        }
    }

    /**
     * 获取sku
     * @param array $sku_id
     * @param bool $return_first
     * @return array
     */
    public function get_sku_by_id(array $sku_id, bool $return_first = false): array
    {
        echo "----test";
        $instance = $this->getModelInstance()->findManyFromCache($sku_id);
        if (empty($instance) || empty($instance->toArray()) || is_null($instance)) {
            echo "db----";
            $instance = $this->getModelInstance()
                ->with(['step_price', 'with_product', 'file_info', 'industry_info'])
                ->whereNull('deleted_at')
                ->whereIn('sku_id', $sku_id)
                ->get();
            $return = $instance->toArray();
            echo "db----end";
        } else {
            echo "caches----";
            // 加载模型缓存
            $instance->loadCache(['step_price', 'with_product', 'file_info', 'industry_info']);
            $return = $instance->toArray();
        }
        if ($return_first) {
            return $return[0] ?? [];
        }
        return $return;
    }
}